package cs.java.event;

import static cs.java.lang.Lang.exception;
import static cs.java.lang.Lang.is;

import cs.java.event.Event.EventRegistration;
import cs.java.lang.Run;

@SuppressWarnings("unchecked") public abstract class Job<Argument> implements Run, Listener {

	protected Argument argument;
	protected EventRegistration registration;
	protected Event<Argument> event;

	protected Job() {}

	public Job(Event<Argument> event) {
		//		for (Event<Void> event : events)
		event.add(this);
	}

	public Job(EventConsumer parent, Event<Argument>... events) {
		for (Event<Argument> event : events)
			add(parent, event);
	}

	public Job(EventConsumer parent, Event<Argument> event) {
		add(parent, event);
	}

	public Job(EventConsumer parent, Event<Argument> event, String id) {
		EventRegistration registration = parent.removeRegistration(id);
		if (is(registration)) registration.cancel();
		parent.addRegistration(id, event.add(this));
	}

	private void add(EventConsumer parent, Event<Argument> event) {
		EventRegistration registration = parent.removeRegistration(event.toString());
		if (is(registration)) throw exception("registering allready registered event");
		parent.addRegistration(event.toString(), event.add(this));
	}

	public <T> void onEvent(Event<T> event, EventRegistration registration, T argument) {
		this.event = (Event<Argument>) event;
		this.registration = registration;
		this.argument = (Argument) argument;
		run();
	}
}